//
//  BaseFlutterViewController.swift
//  DYSwiftFramework
//
//  Created by 黄德玉 on 2022/2/19.
//  Copyright © 2022 none. All rights reserved.
//

import UIKit
import Flutter

class FlutterMixPlugin : NSObject, FlutterPlugin {
    var methodChannel:FlutterMethodChannel?
    static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel.init(name: "mix_info", binaryMessenger: registrar.messenger())
        let instance = FlutterMixPlugin.init()
        instance.methodChannel = channel
        registrar.publish(instance) // publish 后 可以通过你registrar找到plugin
        registrar.addMethodCallDelegate(instance, channel: channel);
    }
    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        // flutter 侧的方法调用
        if call.method == "openPage" {
            Router.push(name: call.arguments as! String)
        }
    }
    func changeFlutterPage(page:String)  {
        methodChannel?.invokeMethod("changePage", arguments: page)
    }
}

class FlutterContentViewController : FlutterViewController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

class BaseFlutterViewController: UIViewController,RouterControllerMixin {
    static var contentVC:FlutterContentViewController?
    weak var plugin:FlutterMixPlugin?
    var isVisible:Bool? {
        didSet {
            if isVisible != true {
                return
            }
            if let vc = BaseFlutterViewController.contentVC?.parent {
                if vc == self {
                    return
                }
            }
            setupChild()
        }
    }
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupChild()
    }
    func setupChild(){
        if BaseFlutterViewController.contentVC == nil {
            BaseFlutterViewController.contentVC = FlutterContentViewController.init(engine: Router.flutterEngine!, nibName: nil, bundle: nil)
        }
        BaseFlutterViewController.contentVC?.view.removeFromSuperview()
        BaseFlutterViewController.contentVC?.removeFromParent()

        addChild(BaseFlutterViewController.contentVC!)
        view.addSubview(BaseFlutterViewController.contentVC!.view)
        BaseFlutterViewController.contentVC!.view.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.equalTo(SCREEN_W)
            make.height.equalTo(SCREEN_H)
        }
    }
    
    func flutterPageChange(name:String) {
        if plugin == nil {
            if let p =  Router.flutterEngine!.valuePublished(byPlugin: "flutter_mix") as? FlutterMixPlugin {
                p.changeFlutterPage(page: name)
            }
        }
    }
}
